//
//  FXStatusPictureView.swift
//  微博(Swift)
//
//  Created by V on 16/1/4.
//  Copyright © 2016年 V. All rights reserved.
//

import UIKit
import SDWebImage


// 可重用ID
private let FXStatusPictureCellId = "FXStatusPictureCellId"
// 每一个条目之前的间距
let itemMargin: CGFloat = 4
// 每一个条目的宽度以及高度
let itemWH = (SCREENW - 2 * FXStatusCellMargin - 2 * itemMargin) / CGFloat(FXStatusPictureMaxCol)





class FXStatusPictureView: UICollectionView, UICollectionViewDataSource {
    
    var picUrls: [FXStatusPictureInfo]? {
        didSet{
            // 1.取出数量 2.更新view大小约束 3.设置测试控件数据
            let count = picUrls?.count ?? 0
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(calcViewSize(count))
            }
            countLabel.text = "\(count)"
            // 当数据设置完成后，更新数据
            reloadData()
        }
    }

    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        dataSource = self
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    // MARK: - 懒加载
    private lazy var countLabel: UILabel = {
        let label = UILabel(textColor: UIColor.lightGrayColor(), fontSize: 35)
        return label
    }()
       
    
    
    private func setupUI(){
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        // 注册cell
        registerClass(FXStatusPictureViewCell.self, forCellWithReuseIdentifier: FXStatusPictureCellId)
        //设置每一个cell的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        // 设置间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
        addSubview(countLabel)
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    
    
    // 转发微博配图视图的大小计算
    private func calcViewSize(count: Int) ->CGSize{
        
        if count == 1{
            let key = picUrls?.first?.thumbnail_pic
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            // 判断从缓存里面在否真的能够取出图片
            if image != nil{
                var size = image.size
                
                // 过窄的处理
                if size.width < 80 {
                    let width: CGFloat = 80
                    let height = width / size.width * size.height
                    size.width = width
                    // 约束最大的高度
                    size.height = height > 150 ? 150 : height
                }else if size.width > 200 {
                    // 图片过宽的处理
                    let width: CGFloat = 200
                    let height = width / size.width * size.height
                    // 约束最大的高度
                    size.height = height > 150 ? 150 : height
                    size.width = width
                    size.height = height
                }
                let layout = collectionViewLayout as!UICollectionViewFlowLayout
                layout.itemSize = size
                return size
            }else{
                // 如果没有取出来，直接返回正方形的 size
                return CGSize(width: itemWH, height: itemWH)
            }
        }else{
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: itemWH, height: itemWH)
        }
        // 计算列数
        let col = (count == 4) ? 2 : (count > FXStatusPictureMaxCol ? FXStatusPictureMaxCol : count)
        // 计算行数
        let row = (count - 1) / FXStatusPictureMaxCol + 1
        // 计算宽度以及高度
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        // print("\(width)")
        // print(itemWH)
        // print("\(itemWH * 2 + 4)")
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
        // 返回结果
        return CGSize(width: width, height: height)
    }
}







// MARK: - 数据源方法 
extension FXStatusPictureView{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(FXStatusPictureCellId, forIndexPath: indexPath) as! FXStatusPictureViewCell
        cell.picUrl = picUrls![indexPath.row]
        return cell
    }
}










// MARK: - 自定义 cell
private class FXStatusPictureViewCell: UICollectionViewCell{
    // 定义外界设置的属性
    var picUrl: FXStatusPictureInfo? {
        didSet{
            if let urlSrting = picUrl?.thumbnail_pic {
                let url = NSURL(string: urlSrting)
                imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    // 懒加载控件
    private lazy var imageView: UIImageView = {
        // 占位图片
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        return imageView
    }()
    
    
    
    
    private func setupUI(){
        addSubview(imageView)
        // 约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
    }
    
}


















